# import numpy as np
# print('================')
# Z = np.random.randint(0,5,(5,5))
# window = 2
# print(Z)
# print(Z.size)
# shape = (Z.shape[0] - window + 1, window, Z.shape[-1])
# strides = (Z.strides[0],) + Z.strides
# print(strides)
# a_rolling = np.lib.stride_tricks.as_strided(Z, shape=shape, strides=strides)
#
# print(a_rolling)
#

# import pandas as pd
# import numpy as np
# pd.set_option('display.max_columns', None)
# pd.set_option('display.max_rows', None)
# from rqalpha.dcdata.utility.time_fuc import num2time
#
# # pd.set_option('display.float_format', lambda x: '%.3f' % x)
# # np.set_printoptions(suppress=True, precision=4, threshold=np.inf)
# path = r"C:\Users\huajia\Desktop\rqalpha3\rqalpha\dcdata\data\spot\1INCHUSDT\daily\aggTrades\1INCHUSDT-aggTrades-2022-03-20.csv"
#
# df = pd.read_csv(path, sep=',', header=None)
# print(df.head(5))
#
# df.iloc[:, 5] = df.iloc[:, 5].map(num2time)
#
# print(df.head(5))
#

# multiIndexFactors = pd.DataFrame()
#
# df = pd.DataFrame({'a': [0, 1, 2, 3], 'b': [4, 1, 3, 6], 'c': [8, 2, 1, 2], 'd': [7, 7, 9, 2]})
# print(df)
# df = df[['a', 'b']]
# df.set_index('a', inplace=True)
# # print(df)
# df = df.iloc[:, 0]
# df.name = 'www'
# print(df)
# multiIndexFactors = multiIndexFactors.append(df)
# factors2 = df.copy()
# factors2.index = [4, 5, 6, 7]
# factors2[:] = [7, 2, 5, 8]
# factors2.name = 'sss'
# print(factors2)
# multiIndexFactors = multiIndexFactors.append(factors2)
# ##多重索引
# print(multiIndexFactors)
# multiIndexFactors.index.set_names(['date'], inplace=True)
# print(multiIndexFactors)
# multiIndexFactors = multiIndexFactors.stack()
# print(multiIndexFactors)
# multiIndexFactors = pd.DataFrame(multiIndexFactors)
# # ## 设置索引名称
# print('++++++++++')
# print(multiIndexFactors)
# multiIndexFactors.index.set_names(['date', 'asset'], inplace=True)
# # ## 设置列名称
# print(multiIndexFactors)
# multiIndexFactors.columns = ['factor_value']
# print(multiIndexFactors)
#
#
#
import datetime
import os
import time
import json
import numpy as np
import pandas as pd
pd.set_option('display.max_columns', None)
pd.set_option('display.max_rows', None)
# file_path = r'C:\Users\huajia\Desktop\rqalpha3\rqalpha\apis'
# files = os.listdir(file_path)
# # print(files)
#
# t_li = {}
# for file in files:
#     temp = os.path.getmtime(os.path.join(file_path, file))
#     temp = time.localtime(temp)
#     temp = time.strftime('%Y-%m-%d %H:%M:%S', temp)
#     t_li[file] = temp
# max_t = sorted(t_li.values())[-2:]
# need_files = []
# for i in max_t:
#     file = [key for key, value in t_li.items() if value == i][0]
#     need_files.append(file)
#
#
# def match_orders_to_df(events):
#     items = []
#     for event in events:
#         args = event["order_record"]
#         # print(args)
#         new_item = {
#             "direction": args["args_"]["direction"],
#             "price": args["price_"],
#             "midp": args["args_"]["remark"]['price'] if 'price' in args["args_"]["remark"].keys() else np.nan,
#             "amount": args["amount_"],
#             "L": args["args_"]["remark"]['long_trade_id'] if 'long_trade_id' in args["args_"]["remark"].keys() else np.nan,
#             "S": args["args_"]["remark"]['short_trade_id'] if 'short_trade_id' in args["args_"]["remark"].keys() else np.nan,
#             "remark": ", ".join(
#                 [f"{k}:{v}" for k, v in args["args_"]["remark"].items()]
#             )
#             if args["args_"]["remark"]
#             else "",
#             "created_at": datetime.datetime.fromtimestamp(
#                 event["created_at"] / 1000.0) - datetime.timedelta(hours=0 if True else 8),
#             }
#         items.append(new_item)
#     return pd.DataFrame.from_records(items)
#
#
# result_li = []
# for file in need_files:
#     with open(os.path.join(file_path, file)) as f:
#         data = json.load(f)
#         send_order_events = data["send_order_events"]
#         match_events = data["match_events"]
#         match_orders_df = match_orders_to_df(match_events)
#         result_li.append(match_orders_df)
# result_df = pd.concat(result_li).sort_values(by=['created_at'])


# print(pd.date_range('2010-01-01', '2020-01-20'))
#
#
# dts = pd.date_range('2010-01-01', '2010-01-02')
#
# dr = pd.Series(data=[1, 2], index=dts)
#
# print(dr)
# dt = pd.date_range('2010-01-02', '2010-01-04')[0]
# print(dt)
#
# tar = dr.get(dt)
# print(tar)
#
# def fun1():
#     a = 0
#     def fun2():
#         nonlocal a
#         a = a+ 2
#     fun2()
#     print(a)
#
# fun1()
#
#
# from collections import OrderedDict
# ss = OrderedDict()
# ss[1] = 'PPPPP'
# ss[2] = 'ssss'
# print()


# class Taget:
#     def __init__(self, id):
#         self.id = id
#
#     def __getitem__(self, item):
#         print('这个方法被调用')
#         return self.id
#
#
# a = Taget('This is id')
# # print(a.id)
# print(a['python'])

# from multiprocessing import freeze_support, Lock, Process, Value
# import time
#
# cnt = Value('i', 0)
# lock = Lock()
#
#
# def my_test(cnt, lock):
#     with lock:
#         time.sleep(0.1)
#         cnt.value += 1
#         print(cnt.value)
#
#
# if __name__ == '__main__':
#     # freeze_support()
#     ps = [Process(target=my_test, args=(cnt, lock)) for i in range(100)]
#     start = time.time()
#     for p in ps:
#         p.start()
#     for p in ps:
#         p.join()
#     print(cnt.value)


# from multiprocessing import Manager, freeze_support, Process, Lock
# import time
#
#
# def my_test(mdict, lock):
#     with lock:
#         mdict['count'] = mdict['count'] + 1
#         print(mdict)
#         time.sleep(0.4)
#
#
# if __name__ == '__main__':
#     start = time.time()
#     freeze_support()
#     mdict = Manager().dict()
#     mdict['count'] = 0
#     lock = Lock()
#     # ps = [Process(target=my_test, args=(mdict,)) for i in range(10)]
#     # for p in ps:
#     #     p.start()
#     # for p in ps:
#     #     p.join()
#     # print(mdict)
#     import concurrent.futures
#     with concurrent.futures.ProcessPoolExecutor(max_workers=8) as executor:
#         for i in range(200):
#             executor.submit(my_test, mdict=mdict, lock=lock)
#


# print([1, *[1,2,3]])


xx = np.array([[1, 2, 3], [4, 6, 5], [9, 8, 9]])
print(xx[0, :])
cc = np.vstack([xx[0, :], xx[1, :]]).T
print(cc)

df = pd.DataFrame(data=xx, columns=['a', 'b', 'c'])
print(df)
# df = df.apply(lambda x: sorted(x), axis=1)
# print(df)
def f(df):
    df = df.sort_values(ascending=False, inplace=True)
    return df
df2 = df.apply(f, axis=1)
print(df2)


